package com.hy.demo.learn.thread.数字加减;

/**
 * <p>
 * 数字加减
 * </p>
 *
 * @author cjl
 * @version 1.0
 * @since 2020-08-27 09:35
 */
public class ThreadDemo {

    public static void main(String[] args) {
        Resource rs=new Resource();
        AddThread addThread=new AddThread(rs);
        SubThread subThread=new SubThread(rs);

        new Thread(addThread,"加法--A").start();
        new Thread(addThread,"加法--B").start();

        new Thread(subThread,"减法--X").start();
        new Thread(subThread,"减法--Y").start();
    }
}


class AddThread implements Runnable{
    private Resource resource;

    public AddThread(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {

        for (int i = 0; i < 50; i++) {

            try {
                this.resource.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class SubThread implements Runnable{
    private Resource resource;

    public SubThread(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {

        for (int i = 0; i < 50; i++) {

            try {
                this.resource.sub();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class Resource{
    private int num=0;
    private boolean flag=true;

    // flag:true 可以进行加法操作，但无法进行减法操作
    // flag:false 可以进行减法操作，单无法进行加法操作

    public synchronized void add() throws Exception {

        if(this.flag==false){
            super.wait();
        }
        Thread.sleep(100);
        this.num++;
        System.out.println(Thread.currentThread().getName()+"正在进行加法操作 num="+this.num);
        this.flag=false;
        super.notifyAll();
    }
    public synchronized void sub() throws Exception {
        if(this.flag==true){
            super.wait();
        }
        Thread.sleep(100);
        this.num--;
        System.out.println(Thread.currentThread().getName()+"正在进行减法操作 num="+this.num);

        this.flag=true;
        super.notifyAll();
    }
}

